#include <iostream>
#include <vector>
#include <cstring>
using namespace std;

const int NUM = 55;
int M, N;
int dx[4] = { 0, 0, 1, -1 };
int dy[4] = { 1, -1, 0, 0 };
bool vis[NUM][NUM] = { 0 };
int dx1[8] = { 0, 0, 1, -1, 1, 1, -1, -1 };
int dy1[8] = { 1, -1, 0, 0, 1, -1, 1, -1 };
bool flag = false;

void dfs_land(vector<vector<char>> map, int i, int j)
{
    vis[i][j] = true;

    for (int k = 0; k < 4; k++)
    {
        int x = i + dx[k], y = j + dy[k];
        if (x >= 1 && x <= M && y >= 1 && y <= N && !vis[x][y] && map[x][y] == '1')
        {
            dfs_land(map, x, y);
        }
    }
}

void dfs_sea(vector<vector<char>> map, int i, int j)
{
    vis[i][j] = true;
    if (i == 0 || j == 0 || i == M + 1 || j == N + 1)
    {
        flag = true;
        return;
    }

    for (int k = 0; k < 8; k++)
    {
        int x = i + dx1[k], y = j + dy1[k];
        if (x >= 0 && x <= M + 1 && y >= 0 && y <= N + 1 && !vis[x][y] && map[x][y] == '0')
        {
            dfs_sea(map, x, y);
        }
    }
}

int main()
{
    int T;
    cin >> T;
    for (int i = 0; i < T; i++)
    {
        int ans = 0;

        cin >> M >> N;
        vector<vector<char>> map(NUM, vector<char>(NUM, 0));
        for (int i = 0; i <= M + 1; i++)
            for (int j = 0; j <= N + 1; j++)
                if (i == 0 || j == 0 || i == M + 1 || j == N + 1) map[i][j] = '0';
                else cin >> map[i][j];

        memset(vis, 0, sizeof(vis));
        vector<pair<int, int>> vec;
        for (int i = 1; i <= M; i++)
        {
            for (int j = 1; j <= N; j++)
            {
                if (!vis[i][j] && map[i][j] == '1')
                {
                    vis[i][j] = true;
                    dfs_land(map, i, j);
                    vec.push_back({ i, j });
                }
            }
        }

        for (auto it : vec)
        {
            memset(vis, 0, sizeof(vis));
            flag = false;
            dfs_sea(map, it.first, it.second);
            if (flag) ans++;
        }

        cout << ans << endl;
    }
    return 0;
}
